<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="栏目列表"
      :columns="columns"
      :request-api="categoryApi.list"
      :searchCol="4"
      :pagination="false">
      <template #tableHeader>
        <el-button type="primary" @click="openDialog()">
          <i class="mr-2 fas fa-plus"></i>
          <span>添加栏目</span>
        </el-button>
      </template>
      <!-- Operation -->
      <template #operation="scope">
        <el-button type="primary" link @click="openDialog(scope.row)">重命名</el-button>
        <el-button type="danger" link @click="deleteCategory(scope.row)">删除</el-button>
      </template>
    </ProTable>

    <!-- 添加/编辑栏目弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="添加/编辑栏目" width="500">
      <el-input v-model="categroyForm.title" placeholder="请输入栏目名称"></el-input>
      <template #footer>
        <div>
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import type { ColumnProps, ProTableInstance } from '@/components/proTable/interface';
import categoryApi from '@/apis/category';
import type { CategoryApiType } from '@/apis/category/namespace';

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 栏目表单
const categroyForm = ref<{ title: string; id?: string }>({ title: '' });

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { prop: 'id', label: '栏目id', width: 100, fixed: 'left' },
  { prop: 'title', label: '栏目名称' },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'center' },
]);

// 打开弹窗框
const dialogFormVisible = ref(false);

const openDialog = (row?: CategoryApiType.Category) => {
  if (row) {
    categroyForm.value = row;
  } else {
    categroyForm.value = { title: '' };
  }
  dialogFormVisible.value = !dialogFormVisible.value;
};

// 添加/编辑栏目
const handleSubmit = async () => {
  if (!categroyForm.value.id) {
    await categoryApi.create(categroyForm.value);
  } else if (categroyForm.value.id) {
    await categoryApi.put({ id: categroyForm.value.id, title: categroyForm.value.title });
  }

  dialogFormVisible.value = false;
  proTable.value?.search();
};

//删除栏目
const deleteCategory = (row: CategoryApiType.Category) => {
  ElMessageBox.confirm('确认删除该栏目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await categoryApi.delete({ id: row.id });
    proTable.value?.search();
  });
};
</script>

<style scoped lang="scss"></style>
